package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    /**
     * 菜单查询
     * @return
     */
    public List<Menu> findMenuByUserUsername(String username) {
        return menuDao.findMenuByUserUsername(username);
    }

    //菜单新增服务
    @Override
    public void add(Menu menu, Integer parentId) {
        if(parentId==null){
            menu.setLevel(1);
        }else {
            menu.setLevel(2);
        }
        menuDao.add(menu);
        Integer menuId = menu.getId();
        Map<String ,Integer> map = new HashMap<>();
        map.put("menuId",menuId);
        map.put("parentId",parentId);
        menuDao.addMenuAndParent(map);
    }


    //分页查询
    @Override
    public PageResult queryPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        Page<Menu> page = menuDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());

    }

    //根据id查询
    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);

    }

    //编辑菜单项
    @Override
    public void edit(Menu menu, Integer pid) {
        if(pid==null){
            menu.setLevel(1);
        }else {
            menu.setLevel(2);
        }
        menuDao.edit(menu);
        Integer id = menu.getId();
        Map<String ,Integer> map = new HashMap<>();
        map.put("menuId",id);
        map.put("parentId",pid);
        menuDao.addMenuAndParent(map);
    }

    //删除
    @Override
    public void delete(Integer id) {
        Integer parentById = menuDao.findParentById(id);
        if(parentById==null){
            Integer sonCount = menuDao.findSonCount(id);
            if(sonCount!=null){
                throw new RuntimeException("父菜单,不能删除");
            }else {
                menuDao.deleteById(id);
            }
        }else {
            menuDao.deleteById(id);
        }
    }


    @Override
    public List<Menu> findAllParent() {
        return menuDao.findAllParent();
    }


    @Override
    public Integer findParentById(Integer id) {
        return menuDao.findParentById(id);
    }
}
